﻿using SkiaSharp;
using SkiaSharp.QrCode;

namespace StarsAdmin.Core.Helpers
{
    /// <summary>
    /// 二维码工具类
    /// <see href="https://cloud.tencent.com/developer/article/2336486"/>
    /// </summary>
    public class QRCodeHelper
    {
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="text">扫描二维码时显示的文本内容，如果是网址自动跳转</param>
        /// <param name="pixel">宽高像素</param>
        /// <returns></returns>
        public static SKData GetQRCode(string text, int pixel = 200, SKEncodedImageFormat type = SKEncodedImageFormat.Jpeg)
        {
            using (var generator = new QRCodeGenerator())
            {
                // 创建二维码（并设置纠错能力中级）
                var createQrCode = generator.CreateQrCode(text, ECCLevel.M);
                var skImageInfo = new SKImageInfo(200, 200);
                // 创建SkiaSharp画布
                using (var surface = SKSurface.Create(skImageInfo))
                {
                    var canvas = surface.Canvas;
                    // 渲染二维码到画布
                    canvas.Render(createQrCode, skImageInfo.Width, skImageInfo.Height);
                    using (var image = surface.Snapshot())
                    using (var data = image.Encode(type, 100))// 编码画布快照为PNG格式的数据
                    {
                        return data;
                    };
                    // 获取画布快照
                    /*
                     using (var stream = File.OpenWrite(@"MyQRCode.png"))
                     {
                         data.SaveTo(stream);// 将数据保存到文件流中，生成二维码图片
                     }
                     */
                }
            }
        }
    }
}